<template>
  <div>
    <el-popover
      placement="right"
      title="温馨提示！！！"
      :width="200"
      trigger="hover"
      content="只有允许上传png,jpg格式的图片,且大小不超过10M,否则会上传失败"
    >
      <template #reference>
        <el-upload
          class="avatar-uploader"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="uploadChange"
        >
          <el-image v-if="imageUrl" :src="imageUrl" class="avatar" fit="cover" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, watch } from "vue"
import { ElMessage } from "element-plus"

// 接受父组件参数
const props = defineProps<{
  upload: (data: FormData) => any // 上传函数
  modelValue: string
}>()

const emit = defineEmits(["update:modelValue"])

// 上传
const uploadChange = async (file: any) => {
  const formData = new FormData()
  formData.append("file", file.raw)
  try {
    const res = await props.upload(formData)
    if (res.code === 1) {
      imageUrl.value = res.data
      emit("update:modelValue", res.data)
    }
  } catch {
    ElMessage({ message: "上传失败", type: "error" })
  }
}

// 图片
const imageUrl = ref("")

watch(
  () => props.modelValue,
  (val: any) => {
    imageUrl.value = val
  }
)
</script>

<style scoped>
::v-deep(.el-upload) {
  width: 200px;
  height: 130px;
}
.avatar-uploader .avatar {
  width: 200px;
  height: 130px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 130px;
  text-align: center;
}
</style>
